package com.bving.crawler.config;

import com.bving.crawler.config.job.CloseConnectJob;
import org.quartz.CronTrigger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

/**
 *
 * @description
 * 定时任务爬取
 *
 */
@Configuration
public class SchedledCfg {

    /**
     * 获取spring容器
     * @return
     */
    @Bean("crawlerAutohomeJobBean")
    public JobDetailFactoryBean crawlerAutohomeJobBean(){
        //创建任务描述的工厂bean
        JobDetailFactoryBean jb = new JobDetailFactoryBean();
        //设置spirng容器的key,任务中可以根据这个key获取spring容器
        jb.setApplicationContextJobDataKey("context");
        //设置任务
        jb.setJobClass(CrawlerAutohomeJobBean.class);
        //设置当没有触发器和任务绑定，不会删除任务
        jb.setDurability(true);
        return jb;
    }

    /**
     * 定义数据爬取的触发器
     * //@Qualifier注解是通过名字注入bean,
     * @return
     */
    @Bean("crawlerAutohomeJobTrigger")
    public CronTriggerFactoryBean crawlerAutohomeJobTrigger(
            @Qualifier(value = "crawlerAutohomeJobBean") JobDetailFactoryBean itemJobBean){
        //创建一个表达式触发器工厂bean
        CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
        //设置任务描述到触发器
        cronTriggerFactoryBean.setJobDetail(itemJobBean.getObject());
        //设置Cron表达式(从第0秒开始每隔5秒执行一次)
        cronTriggerFactoryBean.setCronExpression("0/20 * * * * ? ");
        return cronTriggerFactoryBean;
    }


    /**
     * 定义关闭无效连接任务
     * @return
     */
    @Bean("closeConnectJobBean")
    public JobDetailFactoryBean closeConnectJobBean(){
        //创建任务描述的工厂bean
        JobDetailFactoryBean jb = new JobDetailFactoryBean();
        //设置spirng容器的key,任务中可以根据这个key获取spring容器
        jb.setApplicationContextJobDataKey("context");
        //设置任务
        jb.setJobClass(CloseConnectJob.class);
        //设置当没有触发器和任务绑定，不会删除任务
        jb.setDurability(true);
        return jb;
    }

    // 定义关闭无效连接触发器
    @Bean("closeConnectJobTrigger")
    public CronTriggerFactoryBean closeConnectJobTrigger(
            @Qualifier(value = "closeConnectJobBean") JobDetailFactoryBean itemJobBean) {
        CronTriggerFactoryBean tigger = new CronTriggerFactoryBean();
        tigger.setJobDetail(itemJobBean.getObject());
        tigger.setCronExpression("0/20 * * * * ? ");
        return tigger;
    }

    /**
     * 定义调度器
     * @return
     */
    @Bean
    public SchedulerFactoryBean schedulerFactory(CronTrigger[] cronTriggerImpl) {
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        bean.setTriggers(cronTriggerImpl);
        return bean;
    }
}